<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/8/24 11:38
 */

namespace module\user\front\input;

use app\library\validate\CaptchaValidate;
use mof\Request;

/**
 * 用户注册输入类
 * @property-read   string $username 用户名
 * @property-read  string $password 密码
 * @property-read  string $confirmPassword 确认密码
 * @property-read  string $mobile 手机号
 * @property-read  string $captcha 验证码
 */
class RegisterInput
{
    protected array $attrs = [
        'username', 'password', 'confirmPassword', 'mobile', 'email', 'captcha', 'invite'
    ];

    public function __construct(protected array $data)
    {
    }

    public static function __make(Request $request): static
    {
        CaptchaValidate::register();

        $rules = [
            'username|登录名'          => 'require',
            'password|密码'            => 'require|min:5',
            'confirmPassword|确认密码' => 'require|confirm:password',
        ];
        $message = [
            'username.require'        => '用户名不能为空',
            'password.require'        => '密码不能为空',
            'password.min'            => '密码不能少于5个字符',
            'confirmPassword.require' => '确认密码不能为空',
            'confirmPassword.confirm' => '两次密码不一致',
        ];

        $emailFields = config('user.email_feature', []);
        $mobileFields = config('user.mobile_feature', []);
        if ($useEmail = in_array('register', $emailFields)) {
            $rules['email|邮箱'] = 'require|email|unique:user';
            $rules['emsCaptcha|邮箱验证码'] = 'require|emsCaptcha:email,#register';
            $message['email.email'] = '邮箱格式不正确';
        }
        if ($useMobile = in_array('mobile', $mobileFields)) {
            $rules['mobile|手机号'] = 'require|mobile|unique:user';
            $rules['smsCaptcha|手机验证码'] = 'require|smsCaptcha:mobile,#register';
            $message['mobile.mobile'] = '手机号格式不正确';
        }
        if (empty($useEmail) && empty($useMobile)) {
            $rules['captcha|验证码'] = 'require|imgCaptcha';
        }

        $data = $request->withValidate($rules, $message)->post();
        return new self($data);
    }

    public function __get($name)
    {
        return $this->data[$name] ?? null;
    }
}